package com.j180.servlet;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.j180.bean.ClassBean;
import com.j180.bean.StudentBean;
import com.j180.bean.TeacherBean;
import net.sf.jsqlparser.expression.operators.relational.RegExpMatchOperator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class TestServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

         req.setCharacterEncoding("utf-8");
          resp.setContentType("utf-8");
          resp.setContentType("text/html;charset=utf-8");

        System.out.println("doGet===>>");
        TeacherBean teacherBean = new TeacherBean(1,"菊花老师",null);
        ClassBean classBeanbean = new ClassBean(1,"班级1",null,teacherBean);
        StudentBean studentBean = new StudentBean(1,"学生1",new Date(),"男",classBeanbean);

        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(studentBean);
        //把json格式的字符串响应给客户端
        resp.getWriter().print(json);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doPost====>>");

        req.setCharacterEncoding("utf-8");
        resp.setContentType("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        TeacherBean t1 = new TeacherBean(1,"张老师",null);
        TeacherBean t2 = new TeacherBean(2,"李老师",null);

        ClassBean c1 = new ClassBean(1,"班级1",null,t1);
        ClassBean c2 = new ClassBean(2,"班级2",null,t2);


        StudentBean s1 = new StudentBean(1,"张菊花", new Date(),"男",c1);
        StudentBean s2 = new StudentBean(2,"王菊花", new Date(),"女",c2);

        List<StudentBean> list = new ArrayList<>();
        list.add(s1);
        list.add(s2);

        ObjectMapper objectMapper = new ObjectMapper();

        try {
            String jsonString = objectMapper.writeValueAsString(list);

            System.out.println(jsonString);

            resp.getWriter().print(jsonString);

        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }


    }
}
